package se.webbzon.boltzmann.game.event;

import java.util.Collection;

import se.webbzon.boltzmann.debug.Debug;
import se.webbzon.boltzmann.environment.AbstractEnvironment;
import se.webbzon.boltzmann.game.sequence.Sequence;
import se.webbzon.boltzmann.object.cinema.AbstractCinemaTerminator;
import se.webbzon.boltzmann.world.CinemaWorldLoader;
import se.webbzon.boltzmann.world.WorldLoaderException;
import se.webbzon.oschi01.worldarea.WorldArea;

public class CinemaStartEvent extends AbstractGameEvent {
	
	// The abstract environment of this cinema start event
	private final AbstractEnvironment env;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public CinemaStartEvent(Sequence sequence, String[] arguments) {
		super(arguments);
		env = sequence.getEnvironment();
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override protected void onBegin(WorldArea world) {
		AbstractCinemaTerminator terminator;
		Collection<AbstractCinemaTerminator> terminators = world.findInstances(AbstractCinemaTerminator.class);
		if (terminators.isEmpty())
			terminator = new CinemaTerminator(world);
		else
			terminator = terminators.iterator().next();
		CinemaWorldLoader loader = new CinemaWorldLoader(env,getArgument(0),terminator);
		try {
			WorldArea cinema = loader.load();
			world.gotoWorldArea(cinema);
			if (!terminators.isEmpty())
				world.destroyAll();
		} catch (WorldLoaderException e) {
			Debug.report(e);
			end();
		}
	}

	@Override protected void onEnd() {};
	
	/*============================================================
	Private Classes
	============================================================*/
	
	/** An implemented cinema terminator. **/
	private final class CinemaTerminator extends AbstractCinemaTerminator {

		public CinemaTerminator(WorldArea reality) {
			super(reality);
		}

		@Override public void terminate() {
			end();
		}
		
	}

}
